<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;

class Sale_pay_bill extends Model
{
    /*
     * 开票员（银行单）
     */
    public function getsalebill($res)
    {
        $page = $res['page'];
        $limit = $res['pageSize'];
        if (isset($res['dname']) && $res['dname']) {
            //公司名查询
            $companyname = array_column(model('company')->getcompanyname($res), 'id');
            if ($companyname) {
                $maps['b.co_id'] = array('in', $companyname);
                $maps['b.co_branch_id'] = array('in', $companyname);
            }
            $maps['a.sale_id'] = array('like', '%' . removeBlank($res['dname']) . '%');//订单号
        } else {
            $maps = array();
        }
        if ($res['status'] == 1) {
            $salewhere['a.paytype_id'] = 6;//银行单类型
            $salewhere['c.number'] = ['neq', ''];//必须含有发票单号
//            $salewhere['e.sale_payplan_id'] =array('EXP','IS NULL');//没有登记到关联表
            $salewhere['d.sale_payplan_id'] =null;//没有登记到关联表
            //待开票
            $join = [
                ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
                ['sale_invoice c', 'a.sale_id=c.sale_id', 'LEFT'],//发票表
                ['sale_pay_index d', 'a.id=d.sale_payplan_id', 'LEFT'],//销售订单-付款安排与付款登记-关系表
            ];
            $saledata = Db::name('sale_pay_plan')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->field("a.*,b.priority,b.saler_id,b.co_id,b.co_branch_id,b.accounts_id,c.drawer_id,c.drawer_at,c.number")
                ->page($page, $limit)
                ->select();

            foreach ($saledata as $saledatakey => $saledataval) {
                //获取的是公共的数据
                $resdata = $this->commoendata($saledataval, 1);
                //公司名称
                $saledata[$saledatakey]['company_name'] = $resdata['company_name'];
                //分公司名称
                $saledata[$saledatakey]['company_branch_name'] = $resdata['company_branch_name'];
                //发票号
                $saledata[$saledatakey]['number'] = implode(' ', str_split($saledataval['number'], 4));
                //开票员 开票时间
                $saledata[$saledatakey]['drawername'] = getinfo($saledataval['drawer_id'], 'admin')['nickname'];
                $saledata[$saledatakey]['drawer_date'] = getTimeDate($saledataval['drawer_at'], 12);
                //设置间隔时间
                $timedate = gettime($saledataval['drawer_at'], time());
                $saledata[$saledatakey]['interval_time'] = $timedate['hour'] . ':' . $timedate['min'] . ':' . $timedate['sec'];

                //收款账号
                $saledata[$saledatakey]['account_banknumber'] = $resdata['account_banknumber'];
                $saledata[$saledatakey]['account_bankname'] = $resdata['account_bankname'];

                //销售订单下有多少个付款安排单
                $saledata[$saledatakey]['numone'] = Db::name('sale_pay_plan')->where('sale_id', $saledataval['sale_id'])->count();
                //业务员
                $saledata[$saledatakey]['saler_name'] = $resdata['saler_name'];

                //编辑者 编者时间
                $saledata[$saledatakey]['managename'] = $resdata['managename'];
                $saledata[$saledatakey]['update_date'] = $resdata['update_date'];
                //处理一个付款安排对应多个备注
                $saledata[$saledatakey]['remark'] =getables('sale_payplan_remark', ['sale_payplan_id' => $saledataval['id']], 'id,remark');
            }

            $count = Db::name('sale_pay_plan')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->count();
        } else {
            //已完成 必须是自己 登记7天以内的
            $salewhere['a.update_id'] = session('userid');
            $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
            //7天之前的时间
            $sevenday = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y')) - 1;
            $salewhere['a.update_at'] = ['between', "$sevenday,$endToday"];
            $join = [
                ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
            ];
            $saledata = Db::name('sale_pay_bill')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->field('a.*,b.priority,b.saler_id,b.co_id,b.co_branch_id,b.id as saleid')->page($page, $limit)->select();

            foreach ($saledata as $saledatakey => $saledataval) {
                $resdata = $this->commoendata($saledataval, 2);
                //公司名称
                $saledata[$saledatakey]['company_name'] = $resdata['company_name'];
                //分公司名称
                $saledata[$saledatakey]['company_branch_name'] = $resdata['company_branch_name'];
                //收款账号
                $saledata[$saledatakey]['account_banknumber'] = $resdata['account_banknumber'];
                $saledata[$saledatakey]['account_bankname'] = $resdata['account_bankname'];
                //收款日期
                $saledata[$saledatakey]['paydate'] = getTimeDate($saledataval['pay_day'], 15);
                $saledata[$saledatakey]['create_name'] = getinfo($saledataval['create_id'], 'admin')['nickname'];
                $saledata[$saledatakey]['create_date'] = getTimeDate($saledataval['create_at'], 12);
                $saledata[$saledatakey]['managename'] = $resdata['managename'];
                $saledata[$saledatakey]['update_date'] = $resdata['update_date'];

                //编辑和删除只能显示当天的
                $daytime=$saledataval['create_at']+86400;
                if(time()<$daytime){
                    //可以操作
                    $saledata[$saledatakey]['editdel']='1';
                }else{
                    $saledata[$saledatakey]['editdel']='2';
                }
                //付款登记的备注,一个付款登记只有一个方式
                $saledata[$saledatakey]['remark'] =getables('sale_payreg_remark', ['sale_payreg_id' => $saledataval['sale_payreg_id']], 'id,remark');
            }
            $count = Db::name('sale_pay_bill')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->count();
        }
        //计算每一个标签的数量
        $arrcount = $this->arrcount($res, $maps);
        return array('count' => $count, 'data' => $saledata, 'arrcount' => $arrcount);
    }

    //处理待开票和已完成公共的数据
    protected function commoendata($saledataval, $code)
    {
        $accnumber = '-';
        //收款账号
        if ($code == 1) {
            //待开票中 nt_sale表
            $account_bankinfo = getinfo($saledataval['accounts_id'], 'accounts');
        } else {
            //已完成 nt_sale_pay_bill
            $account_bankinfo = getinfo($saledataval['account_id'], 'accounts');
        }
        if ($account_bankinfo) {
            $accontbankname = getinfo($account_bankinfo['banks_id'], 'banks')['name'];
            $number = substr($account_bankinfo['account_num'], 0, 3) . '***' . substr($account_bankinfo['account_num'], 7);
            $accnumber = $accontbankname . '/' . $number;
        }
        return array(
            'saler_name' => getinfo($saledataval['saler_id'], 'admin')['nickname'], //业务员
            'company_name' => getinfo($saledataval['co_id'], 'company')['name'], //公司名称
            'company_branch_name' => getinfo($saledataval['co_branch_id'], 'co_branch')['name'], //分公司名称
            'account_banknumber' => $accnumber,//收款账号
            'account_bankname' => $account_bankinfo['bankname'],//开户行
            'managename' => getinfo($saledataval['update_id'], 'admin')['nickname'],
            'update_date' => getTimeDate($saledataval['update_at'], 12)
        );
    }

    /*
     * 待开票数量
     * 已经完成数量
     */
    protected function arrcount($res, $maps)
    {
        $ones = $twos = array();
        switch ($res['status']) {
            case '1':
                $ones = $maps;
                break;
            case '2':
                $twos = $maps;
                break;
        }
        $salewhereone['a.paytype_id'] = 6;//银行单类型
        $salewhereone['c.number'] = ['neq', ''];//必须含有发票单号
        $salewhereone['d.sale_payplan_id'] = null;//没有登记到关联表

        $joinone = [
            ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
            ['sale_invoice c', 'a.sale_id=c.sale_id', 'LEFT'],//发票表
            ['sale_pay_index d', 'a.id=d.sale_payplan_id', 'LEFT'],//销售订单-付款安排与付款登记-关系表
        ];
        $one = Db::name('sale_pay_plan')->alias('a')->join($joinone)->where(function ($query) use ($salewhereone) {
            $query->where($salewhereone);
        })->where(function ($query) use ($ones) {
            $query->whereOr($ones);
        })->count();


        $jointwo = [
            ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
        ];
        $salewheretwo['a.update_id'] = session('userid');
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        //7天之前的时间
        $sevenday = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y')) - 1;
        $salewheretwo['a.update_at'] = ['between', "$sevenday,$endToday"];
        $two = Db::name('sale_pay_bill')->alias('a')->join($jointwo)->where(function ($query) use ($salewheretwo) {
            $query->where($salewheretwo);
        })->where(function ($query) use ($twos) {
            $query->whereOr($twos);
        })->count();
        return array(
            'one' => $one == 0 ? '' : $one,
            'two' => $two == 0 ? '' : $two,
        );
    }

    //点击银行单获取的数据
    public function getbankbill($res)
    {
        $accnumber = '';
        //这里的也就是一个销售订单对应一个发票登记
        $map['a.id'] = $res['sale_id'];
        $join = [
            ['sale_invoice b', 'a.id=b.sale_id', 'LEFT'],//发票登记表
        ];
        $saleresinfo = Db::name('sale')->alias('a')->where($map)->join($join)->field('a.*,b.number')->find();

        $account_bankinfo = getinfo($saleresinfo['accounts_id'], 'accounts');
        if ($account_bankinfo) {
            $accontbankname = getinfo($account_bankinfo['banks_id'], 'banks')['name'];
            $number = substr($account_bankinfo['account_num'], 0, 3) . '***' . substr($account_bankinfo['account_num'], 7);
            $accnumber = $accontbankname . '/' . $number;
        }
        $companyinfo = getinfo($saleresinfo['co_id'], 'company');
        $combranchinfo = getinfo($saleresinfo['co_branch_id'], 'co_branch');
        //左侧
        $array = array(
            'sale_id' => $saleresinfo['id'],
            'company_name' => $companyinfo['name'],
            'regno' => $companyinfo['regno'],//营业号
            'taxno' => $companyinfo['taxno'],//税号
            'co_branch_name' => $combranchinfo['name'],
            'regnos' => $combranchinfo['regno'],
            'taxnos' => $combranchinfo['taxno'],
            'number' => implode(' ', str_split($saleresinfo['number'], 4)),//发票号
            'createname' => getinfo($saleresinfo['create_id'], 'admin')['nickname'],//开票人
            'createdate' => getTimeDate($saleresinfo['create_at'], 12),//开票时间
            'accountname' => $accnumber,//存入账号
            'accountnum' => $account_bankinfo['bankname'],
        );
        //右侧  销售订单下付款安排（并且查看付款安排的是填写流水号，有确认者，不能再进行编辑银行单号）
        $wherepay['a.sale_id'] = $res['sale_id'];
        $joinpay = [
            ['sale_pay_index b', 'a.id=b.sale_payplan_id', 'LEFT'],//销售订单-付款安排与付款登记-关系表
            ['sale_payreg c', 'b.sale_payreg_id=c.id', 'LEFT'],//付款登记表
            ['sale_pay_bill d', 'c.id=d.sale_payreg_id', 'LEFT'],//银行单表
        ];
        $data = Db::name('sale_pay_plan')->alias('a')->join($joinpay)->where($wherepay)->field('a.id,a.amount,a.pay_day,c.check_id,d.number')->select();
        foreach ($data as $datakey => $dataval) {
            $data[$datakey]['pay_date'] = getTimeDate($dataval['pay_day'], 15);
            if ($dataval['check_id']>0) {
                $data[$datakey]['isdisables'] = true;
            } else {
                $data[$datakey]['isdisables'] = false;
            }
        }
        return array('leftdata' => $array, 'rightdata' => $data);
    }

    //点击保存后进行的数据提交
    public function savebill($res)
    {
        $data = array();
        foreach ($res['right'] as $reskey => $resval) {
            if (!$resval['check_id']) {
                if (!$resval['number']) {
                    return array('msg' => '请填写完整要登记的数据', 'status' => 2);
                    exit();
                } else {
                    $data[] = array('id' => $resval['id'], 'number' => $resval['number']);
                }
            }
        }
        if ($data) {
            //将数据登记到付款登记表 付款登记备注表 银行单表  销售表与付款登记表（关联表）
            foreach ($data as $datakey => $dataval) {
                //这里的需要判断该数据是添加还是编辑的
                $nt_sale_pay_info = Db::name('sale_pay_index')->where('sale_payplan_id', $dataval['id'])->find();
                if ($nt_sale_pay_info) {
                    //编辑
                    $update['update_id'] = session('userid');
                    $update['update_at'] = time();
                    $update['number'] = $dataval['number'];
                    Db::name('sale_pay_bill')->where('sale_payreg_id', $nt_sale_pay_info['sale_payreg_id'])->update($update);
                } else {
                    //添加
                    //通过付款安排id获取相关数据
                    $wherepay_play['a.id'] = $dataval['id'];
                    $join = [
                        ['sale b', 'a.sale_id=b.id', 'LEFT'],//销售表
                    ];
                    $saleinfo = Db::name('sale_pay_plan')->alias('a')->join($join)->where($wherepay_play)->field('a.*,b.co_id,b.accounts_id')->find();
                    $sale_pay_indexinsert['co_id'] = $sale_payreginsert['co_id'] = $saleinfo['co_id'];
                    $sale_payreginsert['paytype_id'] = $saleinfo['paytype_id'];
                    $sale_pay_billinsert['pay_day'] = $sale_payreginsert['pay_day'] = $saleinfo['pay_day'];
                    $sale_pay_billinsert['amount'] = $sale_payreginsert['amount'] = $saleinfo['amount'];
                    $sale_pay_billinsert['create_id'] = $sale_pay_billinsert['update_id'] = $sale_remark['update_id'] = $sale_payreginsert['create_id'] = $sale_payreginsert['update_id'] = session('userid');
                    $sale_pay_billinsert['update_at'] = $sale_pay_billinsert['create_at'] = $sale_remark['update_at'] = $sale_payreginsert['create_at'] = $sale_payreginsert['update_at'] = time();
                    //写入付款登记表
                    $insertidone = Db::name('sale_payreg')->insertGetId($sale_payreginsert);

                    //写入备注表
                    $sale_pay_billinsert['sale_payreg_id'] = $sale_pay_indexinsert['sale_payreg_id'] = $sale_remark['sale_payreg_id'] = $insertidone;
                    //写入付款安排表与付款登记关联表
                    $sale_pay_billinsert['sale_id'] = $sale_pay_indexinsert['sale_id'] = $saleinfo['sale_id'];
                    $sale_pay_indexinsert['sale_payplan_id'] = $saleinfo['id'];
                    $insertidthree = Db::name('sale_pay_index')->insert($sale_pay_indexinsert);

                    //写入到银行单表
                    $sale_pay_billinsert['number'] = $dataval['number'];
                    $sale_pay_billinsert['account_id'] = $saleinfo['accounts_id'];
                    $insertfour = Db::name('sale_pay_bill')->insert($sale_pay_billinsert);

                    //这里的备注可能是多个
                    $remarks=Db::name('sale_payplan_remark')->where('sale_payplan_id',$saleinfo['id'])->field('remark')->select();
                    foreach ($remarks as $remarkskey=>$remarksval){
                        $sale_remark['remark'] = $remarksval['remark'];
                        $insertidtwo = Db::name('sale_payreg_remark')->insertGetId($sale_remark);
                    }
                }
            }
        }
        return array('status' => '1', 'msg' => '保存成功');
    }

    //删除银行单
    public function delbill($res)
    {
        //通过银行单id，删除相关的数据
        $sale_billinfo = getinfo($res['id'], 'sale_pay_bill');
        //如果该订单已经确认收款了就无法删除
        if ($sale_billinfo['check_id'] > 0) {
            return array('msg' => '该银行单已经确认收款无法删除', 'status' => 0);
            exit();
        } else if ($res['code'] == 1) {
            //假删除
            $delupdate['del_id'] = session('userid');
            $delupdate['del_at'] = time();
            $delid = $this->where('id', $res['id'])->update($delupdate);
        } else if ($res['code'] == 2) {
            //关联表
            Db::name('sale_pay_index')->where('sale_payreg_id', $sale_billinfo['sale_payreg_id'])->delete();
            //付款登记表
            Db::name('sale_payreg')->where('id', $sale_billinfo['sale_payreg_id'])->delete();
            //付款登记备注表
            Db::name('sale_payreg_remark')->where('sale_payreg_id', $sale_billinfo['sale_payreg_id'])->delete();
            // 删除银行单表
            Db::name('sale_pay_bill')->where('id', $res['id'])->delete();
        }
        return array('msg' => '删除成功', 'status' => 1);
    }
}